/**
 * Android FriendFeed Client
 * Copyright (C) 2010 E & B Labs
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package net.eblabs.androidfriendfeedclient;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

import net.eblabs.friendfeed.FriendFeedAPI;

/**
 * @author epplestun
 */
public class FriendfeedClientActivity extends Activity {
    /* {@inheritDoc}. */
    private ArrayList<FriendfeedEntry> mEntries = null;
    /* {@inheritDoc}. */
    private FriendfeedAdapter mAdapter;
    /* {@inheritDoc}. */
    private ListView list;
    /* {@inheritDoc}. */
    private FriendFeedAPI ffapi;
    /* {@inheritDoc}. */
    private Integer selectedItem;
    /* {@inheritDoc}. */
    private FriendfeedEntry selectedEntry;

    /* {@inheritDoc}. */
    @Override
    public void onCreate(final Bundle icicle) {
            super.onCreate(icicle);
            setContentView(R.layout.main);
            setTitle(R.string.app_name);
            refresh();
            registerForContextMenu(list);
    }

    /* {@inheritDoc}. */
    @Override
    public final boolean onCreateOptionsMenu(final Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    /* {@inheritDoc}. */
    @Override
    public final boolean onOptionsItemSelected(final MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_add_entry:
                addEntry();
            case R.id.menu_refresh:
                refresh();
                return true;
            case R.id.menu_settings:
                settings();
                return true;
            case R.id.menu_quit:
                quit();
                return true;
            default:
                return false;
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        this.selectedEntry = this.mAdapter.getItem(this.selectedItem);
        final Preferences preferences = Preferences.getInstance(this);

        if (v.getId() == R.id.list) {
            menu.setHeaderTitle(R.string.context_menu_title);
            menu.add(1, 0, 0, R.string.context_menu_comment);

            if (this.selectedEntry.userLikesEntry(
                    preferences.getUsername()) == true) {
                menu.add(2, 2, 0, R.string.context_menu_i_unlike);
            } else {
                menu.add(2, 1, 0, R.string.context_menu_i_like);
            }

            //menu.add(3, 2, 0, R.string.context_menu_share);
            //menu.add(4, 3, 0, R.string.context_menu_hide);
            menu.add(5, 4, 0, R.string.context_menu_view_comments);
            //menu.add(6, 5, 0, R.string.context_menu_view_entry);
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        final Activity activity = this;

        if (this.selectedItem < 0) {
            Toast message = Toast.makeText(getApplicationContext(),
                    "Es necesario seleccionar una entrada", Toast.LENGTH_LONG);
            message.show();
        } else {
            this.selectedEntry = this.mAdapter.getItem(this.selectedItem);
            switch (item.getItemId()) {
                case 0: // Add comment
                    addComment();
                    break;

                case 1: // Me gusta
                    likeOrUnlikeEntry("like");
                    break;

                case 2: // Ya no me gusta
                    likeOrUnlikeEntry("like/delete");
                    break;

                    /*
                case 2: // Compartir
                    setTitle("Selected item: " + item.getItemId());
                    break;

                case 3: // Ocultar
                    hideEntry(this.selectedEntry.getId());
                    break;
                    */
                case 4: // View comments
                    //setTitle("View comments of " + item.getItemId());
                    viewEntryComments();
                    break;
            }
        }
        return true;
    }

    /**
     * Formato de cadena: 2010-02-12T14:08:17Z
     * @param date
     * @return
     */
    public String timeAgoDate(String date) {
        String year = date.substring(0, 4);
        String month = date.substring(5, 7);
        String day = date.substring(8, 10);
        String hours = date.substring(11, 13);
        String minutes = date.substring(14, 16);
        String seconds = date.substring(17, 19);

        return hours + ":" + minutes;
    }

    /**
     * Finaliza la aplicación.
     */
    private void quit() {
        int pid = android.os.Process.myPid();
        android.os.Process.killProcess(pid);
    }

    /**
     * Abre la actividad de configuraciones.
     */
    private void settings() {
        Intent myIntent = new Intent(this, LoginSettingsActivity.class);
        startActivity(myIntent);
    }

    /**
     * Abre la actividad de nueva entrada
     */
    private void addEntry() {
        Intent myIntent = new Intent(this, FriendfeedAddEntryActivity.class);
        startActivity(myIntent);
    }

    private void refresh() {
        try {
            Preferences preferences = Preferences.getInstance(this);
            this.ffapi = FriendFeedAPI.getInstance(
                    preferences.getUsername(),
                    preferences.getRemoteKey());
            this.mEntries = FriendfeedEntry.entriesToArrayList(this.ffapi
                    .getFriendsTimeline().getJSONArray("entries"));
            this.mAdapter = new FriendfeedAdapter(this, R.layout
                    .friendfeedentryrow, this.mEntries);
            this.list = (ListView) findViewById(R.id.list);
            this.list.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> av, View v,
                        int position, long id) {
                    selectedItem = position;
                }
            });
            this.list.setOnItemSelectedListener(new OnItemSelectedListener() {

                public void onItemSelected(AdapterView<?> av, View v,
                        int position, long id) {
                    selectedItem = position;
                }

                public void onNothingSelected(AdapterView<?> av) {
                }
            });
            this.list.setAdapter(this.mAdapter);
        } catch (Exception ex) {
            Log.e(FriendfeedClientActivity.class.getName(),
                    ex.toString(), ex);
            Toast message = Toast.makeText(getApplicationContext(),
                    ex.toString(), Toast.LENGTH_LONG);
            message.show();
        }
    }

    private void addComment() {
        Intent myIntent = new Intent(this, FriendfeedAddCommentActivity.class);
        myIntent.putExtra("entry", this.selectedEntry.toBundle());

        startActivity(myIntent);
    }

    private void likeOrUnlikeEntry(String type) {
        final Activity activity = this;
        final Preferences preferences = Preferences.getInstance(this);

        try {
            FriendFeedAPI api = FriendFeedAPI.getInstance(
                    preferences.getUsername(), preferences.getRemoteKey());
            api.likeOrUnlikeEntry(this.selectedEntry.getId(), type);

            if(type.equals("like"))
                Toast.makeText(activity, R.string.i_like_entry_ok,
                        Toast.LENGTH_LONG).show();
            else
                Toast.makeText(activity, R.string.i_unlike_entry_ok,
                        Toast.LENGTH_LONG).show();
        } catch(Exception ex) {
            Toast.makeText(activity, ex.getMessage(), Toast.LENGTH_LONG).show();
        }       
    }

    private void viewEntryComments() {
        Intent myIntent = new Intent(this,
                FriendfeedCommentsListActivity.class);
        myIntent.putExtra("entry", this.selectedEntry.toBundle());

        startActivity(myIntent);
    }

    /*
    private void hideEntry(String entry) {
        final Activity activity = this;
        final Preferences preferences = Preferences.getInstance(this);

        FriendFeedAPI api = FriendFeedAPI.getInstance(
                preferences.getUsername(), preferences.getRemoteKey());
        try {
            api.hideEntry(this.selectedEntry.getId());
            Toast.makeText(activity, R.string.i_like_entry_ok,
                    Toast.LENGTH_LONG).show();
        } catch (URISyntaxException ex) {
            Logger.getLogger(FriendfeedClientActivity.class.getName())
                    .log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(FriendfeedClientActivity.class.getName())
                    .log(Level.SEVERE, null, ex);
        } catch (ApiException ex) {
            Logger.getLogger(FriendfeedClientActivity.class.getName())
                    .log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FriendfeedClientActivity.class.getName())
                    .log(Level.SEVERE, null, ex);
        } catch (JSONException ex) {
            Logger.getLogger(FriendfeedClientActivity.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
    }
    */
}
